// api/index.js

// 基础配置
const BASE_URL = 'http://localhost:8080/app';

// 请求拦截器
const requestInterceptor = (config) => {
	// 获取token，如果存在则添加到请求头
	const token = uni.getStorageSync('token');
	if (token) {
		config.header = {
			...config.header,
			'token': token
		};
	}

	return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
	// 统一处理响应
	if (response.statusCode === 200) {
		// 根据业务状态码处理
		if (response.data.code === 401) {
			// token失效，清除本地存储并跳转到登录页
			uni.clearStorageSync();
			uni.showToast({
				title: '登录已过期，请重新登录',
				icon: 'none'
			});

			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/login/login'
				});
			}, 1500);

			return Promise.reject(new Error('登录已过期'));
		}

		return response.data;
	}

	// 处理HTTP错误
	uni.showToast({
		title: `请求失败: ${response.statusCode}`,
		icon: 'none'
	});

	return Promise.reject(new Error(`HTTP错误: ${response.statusCode}`));
};

// 通用请求方法
const request = (options) => {
	// 合并选项
	const config = {
		url: `${BASE_URL}${options.url}`,
		...options
	};

	// 应用请求拦截器
	const finalConfig = requestInterceptor(config);

	return new Promise((resolve, reject) => {
		uni.request({
			...finalConfig,
			success: (res) => {
				try {
					const result = responseInterceptor(res);
					resolve(result);
				} catch (error) {
					reject(error);
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none'
				});
				reject(new Error('网络错误'));
			}
		});
	});
};

// 导出各种请求方法
export default {
	get: (url, data = {}, options = {}) => {
		return request({
			url,
			data,
			method: 'GET',
			...options
		});
	},

	post: (url, data = {}, options = {}) => {
		return request({
			url,
			data,
			method: 'POST',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				...options.header
			},
			...options
		});
	},

	put: (url, data = {}, options = {}) => {
		return request({
			url,
			data,
			method: 'PUT',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				...options.header
			},
			...options
		});
	},

	delete: (url, data = {}, options = {}) => {
		return request({
			url,
			data,
			method: 'DELETE',
			...options
		});
	}
};